package org.example.controller;

import org.example.domain.ResponseResult;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author beikbei
 * @version 1.0
 * @description: TODO
 * @date 2024/5/11 9:47
 */

@RestController
@RequestMapping("/")
public class HelloController {
    @RequestMapping("/hello")
    public String hello() {
        return "Hello Spring Boot!";
    }

    // 获取当前登录的用户名
    @RequestMapping("/users/username")
    public String getUsername() {
        // 1. 获取会话对象
        SecurityContext context = SecurityContextHolder.getContext();
        // 2. 获取认证对象
        Authentication authentication = context.getAuthentication();
        // 3. 获取登录用户信息
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        return userDetails.getUsername();
    }

    @RequestMapping("/testCors")
    @PreAuthorize("hasAnyRole('admin','system:dept:query')")
//    @PreAuthorize("@ex.hasAuthority('system:dept:query')")
    public ResponseResult testCors() {
        return new ResponseResult(200, "testCors");
    }
}
